/*
@STI LICENSE
(C) 2006-2008 Universit�t Innsbruck.

This file is part of myOntology.

myOntologyis free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

myOntologyis distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with myOntology.  If not, see <http://www.gnu.org/licenses/>.

@STI LICENSE */
package org.myontology.controller;



import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

import org.apache.log4j.Logger;

public abstract class AbstractController {

	public void injectDepencies(Object action, AttributeHolder attributes) {
		dIController.injectDepencies(action, attributes);
	}

	public AbstractController() {
		init();
		dIController.implement(AbstractController.class, this);
	}
	
	private Set<Selector> selectors = new CopyOnWriteArraySet<Selector>();
	
	public Selector addSelector(Selector sel) {
		selectors.add(sel);
		sel.setController(this);
		return sel;
	}
	
	protected DIController dIController= new DIController();
	
	protected Logger logger = Logger.getLogger(getClass());
	
	public abstract void init();
	
	protected void executeAction(Action action,AttributeHolder attributes) throws Exception{
		logger.debug("executing: "+action.toString());
		Action executingAction = action.cloneMe();
		dIController.injectDepencies(executingAction,attributes);
		executingAction.execute(attributes);
	}
	
	public PageProvider execute(AttributeHolder attributes) {
		
		PageProvider prov = null;
		try {
			for (Iterator<Selector> it = selectors.iterator();it.hasNext();) {
				Selector selector = it.next();
				PageProvider tmp = selector.select(attributes);
				if (tmp!=null && prov!=null)
					logger.error("duplicate result for selector "+selector.toString());
				else if (tmp!=null)
					prov=tmp;
			}
			dIController.finishDependencies(attributes);
		} catch (Exception e) {
			logger.error("Exception in Action execution: ",e);
			dIController.cleanDependencies(attributes);
		}
		
		return prov;
	}
	
	
}
